﻿using System;
using YAWD.Utils;
using System.Collections.Generic;
using YAWD.Properties;
using System.Text;
using YAWD.BL.Services;

namespace YAWD.BL.Providers
{
    class InterfaceLIFT : IProvider
    {
        public string URL { get; set; }
        public string Path { get; set; }
        public string FirstImage { get; set; }
        public string LastDwImage { get; set; }
        public DateTime LastUpdated { get; set; }
        public string LastId { get; set; }

        private bool _isCancelationPending;
        private double _current;
        private string _currentImage = string.Empty;
        private IList<string> _images;

        public double Current
        {
            get { return this._current; }
            set
            {
                this._current = value;
                OnProgressChanged(EventArgs.Empty);
            }
        }
        public string CurrentImage
        {
            get { return this._currentImage; }
            set
            {
                this._currentImage = value;
                OnCurrentImageChanged(EventArgs.Empty);
            }
        }
        public IList<string> Images
        {
            get { return this._images; }
            set
            {
                this._images = value;
                OnImagesChanged(EventArgs.Empty);
            }
        }

        public event EventHandler ProgressChanged;
        public event EventHandler CurrentImageChanged;
        public event EventHandler ImagesChanged;

        public IProvider Init()
        {
            return Util.ReadProviderSettings(this);
        }
        protected virtual void OnProgressChanged(EventArgs e)
        {
            if (this.ProgressChanged != null)
                this.ProgressChanged(this, e);
        }
        protected virtual void OnCurrentImageChanged(EventArgs e)
        {
            if (this.CurrentImageChanged != null)
                this.CurrentImageChanged(this, e);
        }
        protected virtual void OnImagesChanged(EventArgs e)
        {
            if (this.ImagesChanged != null)
                this.ImagesChanged(this, e);
        }

        public int getAll()
        {
            int start;
            if (int.TryParse(FirstImage, out start) == true)
                return getImages(start);
            else
                return 0;
        }
        private int getImages(int start)
        {
            this._isCancelationPending = false;

            int downloadedImage = 0;
            int end = getLatest();

            int nbrItems = end - start;
            double interleave = (double)100 / nbrItems;

            Settings settings = Settings.Default;
            string initPath;
            if (string.IsNullOrWhiteSpace(settings.WallPapersPath))
                initPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            else
                initPath = settings.WallPapersPath;

            IList<string> resolutions = ResolutionServices.GetEnabledResolutions();

            for (int i = start; i < end; i++)
            {
                //exit if the user cancels
                if (this._isCancelationPending == true)
                {
                    Util.SaveToConfigFile("LastUpdated", DateTime.Now.ToShortDateString(), this);
                    this.LastUpdated = DateTime.Now;
                    return downloadedImage;
                }

                Current += interleave;

                string url = URL + i + @"/";

                string webPage = Util.GetHtmlPage(url, Encoding.UTF8);
                if (webPage != null)
                {
                    string strParsing = @"javascript:imgload('";
                    int intTemp = webPage.IndexOf(strParsing);

                    if (intTemp > -1)
                    {
                        webPage = webPage.Substring(intTemp + strParsing.Length);
                        strParsing = @"'";
                        string fileName = webPage.Substring(0, webPage.IndexOf(strParsing)).Trim();

                        foreach (string item in resolutions)
                        {
                            string file = fileName + "_" + item + ".jpg";
                            url = @"http://interfacelift.com/wallpaper/7yz4ma1/" + i.ToString().PadLeft(5, '0') + "_" + file;
                            webPage = Util.GetHtmlPage(url, Encoding.UTF8);
                            if (webPage.Contains("Error 404") == false && webPage.Contains("Invalid parameter: res") == false)
                            {
                                if (Util.GetImage(url, string.Empty,
                                                                                    this.GetType().Name, file,true) > 0)
                                {
                                    downloadedImage++;
                                    this.LastDwImage = i.ToString();
                                    Util.SaveToConfigFile("LastDwImage", this.LastDwImage, this);
                                    CurrentImage = this.LastDwImage;
                                    Images = Util.LoadImage(Utils.Providers.InterfaceLIFT, initPath);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            this.LastUpdated = DateTime.Now;
            Util.SaveToConfigFile("LastUpdated", DateTime.Now.ToShortDateString(), this);
            return downloadedImage;
        }
        public int update()
        {
            int start;

            if (int.TryParse(LastDwImage, out start) == true)
                return getImages(start);
            else if (int.TryParse(FirstImage, out start) == true)
                return getImages(start);
            else
                return 0;
        }
        public void CancelAsync()
        {
            this._isCancelationPending = true;
        }
        private int getLatest()
        {
            string webPage = Util.GetHtmlPage("http://interfacelift.com/wallpaper_beta/rss/", Encoding.UTF8);
            string strParsing = @"/details/";
            int intTemp = webPage.IndexOf(strParsing);
            if (intTemp > -1)
            {
                webPage = webPage.Substring(intTemp + strParsing.Length);
                strParsing = @"/";
                intTemp = webPage.IndexOf(strParsing);
                webPage = webPage.Substring(0, intTemp);

                int results;
                if (int.TryParse(webPage, out results) == true)
                    return results;

            }
            return 0;
        }

    }
}

